<template>
  <view class="category-page">
    <view class="category-container">
      <!-- 左侧主分类导航 -->
      <scroll-view class="category-nav" :scroll-y="true">
        <view
          v-for="(item, index) in mainCategories"
          :key="item.id"
          class="nav-item"
          :class="{ active: activeIndex === index }"
          @click="selectCategory(index)"
        >
          {{ item.name }}
        </view>
      </scroll-view>

      <!-- 右侧服务展示 (重构) -->
      <scroll-view class="service-display" :scroll-y="true">
        <!-- 加载中提示 -->
        <view v-if="isLoading" class="loading-state">加载中...</view>
        
        <!-- 数据展示 -->
        <view v-else-if="subCategoriesWithServices.length > 0">
          <view v-for="subCategory in subCategoriesWithServices" :key="subCategory.categoryId" class="service-block">
            <h3 class="block-title">{{ subCategory.categoryName }}</h3>
            <view class="service-grid">
              <view
                v-for="service in subCategory.services"
                :key="service.serviceId"
                class="service-item"
                @click="gotoServiceDetail(service.serviceId)"
              >
                <image class="service-image" :src="service.serviceHeadImg" mode="aspectFill"></image>
                <text class="service-name">{{ service.serviceMainName }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 空状态提示 -->
        <view v-else class="empty-state">暂无服务</view>

      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { request } from '@/utils/request.js';
import { BASE_URL } from '@/utils/config.js';

// ---- 响应式状态定义 ----
const mainCategories = ref([]); // 左侧主分类列表
const activeIndex = ref(0);     // 当前选中的主分类索引
const subCategoriesWithServices = ref([]); // 右侧展示的数据
const isLoading = ref(false); // 用于控制加载状态

// ---- API 请求方法 ----

/**
 * @description 获取主分类列表
 */
const fetchMainCategories = async () => {
  try {
    const data = await request({
      url: '/categories',
      method: 'POST',
    });
    // 数据转换
    mainCategories.value = data.map(cat => ({
      id: cat.categoryId,
      name: cat.categoryName,
    }));
    
    // 获取主分类后，如果列表不为空，则自动加载第一个分类下的服务
    if (mainCategories.value.length > 0) {
      fetchServicesByCategoryId(mainCategories.value[0].id);
    }
  } catch (error) {
    console.error('获取主分类失败:', error);
  }
};

/**
 * @description 根据主分类ID获取其下的子分类和服务列表
 * @param {number} categoryId - 主分类ID
 */
const fetchServicesByCategoryId = async (categoryId) => {
  if (!categoryId) return;
  isLoading.value = true;
  subCategoriesWithServices.value = []; // 先清空
  try {
    const data = await request({
      url: '/services',
      method: 'POST',
      data: {
        categoryPid: categoryId
      }
    });
    // 数据转换，主要是拼接图片URL
    subCategoriesWithServices.value = data.map(subCat => ({
      ...subCat,
      services: subCat.services.map(service => ({
        ...service,
        // [关键] 拼接完整的图片URL
        serviceHeadImg: `${BASE_URL}${service.serviceHeadImg}`
      }))
    }));
  } catch (error) {
    console.error(`获取ID为 ${categoryId} 的服务失败:`, error);
  } finally {
    isLoading.value = false;
  }
};


// ---- 事件处理方法 ----

/**
 * @description 切换选中的主分类
 * @param {number} index - 点击的分类索引
 */
const selectCategory = (index) => {
  activeIndex.value = index;
  // 切换后，根据新的索引获取对应的主分类ID，并发起请求
  const categoryId = mainCategories.value[index]?.id;
  fetchServicesByCategoryId(categoryId);
};

/**
 * @description 跳转到服务详情页
 * @param {number} serviceId - 服务的ID
 */
const gotoServiceDetail = (serviceId) => {
  uni.navigateTo({
    url: `/pages/service-detail/service-detail?id=${serviceId}`,
  });
};


// ---- 生命周期钩子 ----
onLoad(() => {
  fetchMainCategories();
});
</script>

<style lang="scss" scoped>
.category-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.category-container {
  display: flex;
  flex-grow: 1;
  overflow: hidden;
}

/* 左侧导航样式 (保持不变) */
.category-nav {
  width: 180rpx;
  background-color: $uni-bg-color;
  flex-shrink: 0;
  .nav-item {
    height: 110rpx; display: flex; justify-content: center;
    align-items: center; font-size: 28rpx; color: $uni-text-color;
    position: relative; transition: all 0.3s;
    &.active {
      background-color: $uni-bg-color-white;
      font-weight: 500;
      color: $uni-primary;
      &::before {
        content: ''; position: absolute; left: 0; top: 50%;
        transform: translateY(-50%); width: 8rpx; height: 48rpx;
        background-color: $uni-primary; border-radius: 0 8rpx 8rpx 0;
      }
    }
  }
}

/* 右侧展示区样式 (重构) */
.service-display {
  flex-grow: 1;
  background-color: $uni-bg-color-white;
  padding: 30rpx;
  
  .service-block {
    margin-bottom: 40rpx;
    &:last-child {
      margin-bottom: 0;
    }
  }

  .block-title {
    font-size: 30rpx;
    font-weight: 500;
    margin-bottom: 30rpx;
  }
  
  .service-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr); // 保持三列布局
    gap: 30rpx;
    row-gap: 40rpx;
  }
  
  .service-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16rpx;
    
    .service-image {
      width: 140rpx; // 调整图片大小
      height: 140rpx;
      border-radius: 16rpx;
      background-color: $uni-bg-color; // 图片加载前的占位背景
    }
    
    .service-name {
      font-size: 26rpx;
      color: $uni-text-color;
      // 最多显示两行，超出省略
      text-align: center;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
  }

  .loading-state, .empty-state {
    text-align: center;
    padding-top: 200rpx;
    color: $uni-text-color-light;
  }
}
</style>